<?php
namespace app\api\service;

use think\Exception;
use think\Log;
use think\Db;
use common\util\Tools;
class WithdrawService {

    public static function withdraw($mid, $money, $all, $bankId) {
        $data = [
            'mid' => $mid,
            'type' => 2,
            'money' => $money,
            'ifpass' => 0,
            'cash_name' => '提现',
            'addtime' => Tools::getCurDate(),
            'bank_id' => $bankId
        ];
        
        // 启动事务
        Db::startTrans();
        try {
            $member = Db::name('member')->lock(true)->find($mid);
            $account = $member['rewardaccount'];
            if (empty($all)) {
                if ($account < $money) {
                    throw new Exception('余额不足');
                }
            } else {
                if ($account <= 0) {
                    throw new Exception('余额不足');
                }
                $money = $account;
            }
            $data['money'] = $money;
            $id = Db::name('recharge')->insert($data);
            Db::name('member')->where('id', $mid)->setDec('rewardaccount', $money);
            Db::name('member')->where('id', $mid)->setInc('rewardaccount_lock', $money);
            
            // 提交事务
            Db::commit();
            return [true,''];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            Log::write("withdraw error,msg:".$e->getMessage());
            return [false,$e->getMessage()];
        }
    }
}